package com.huiminpay.paymentagent.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.Paragraph;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayBean;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.paymentagent.constants.AliCodeConstants;
import com.huiminpay.paymentagent.message.PayProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Service
public class PayChannelAgentServiceImpl implements PayChannelAgentService {
    //对接支付宝下单接口
    //返回支付宝响应数据
    @Autowired
    private PayProducer payProducer;
    @Override
    public PaymentResponseDTO createPayOrderByAliWAP(AliConfigParam aliConfigParam, AlipayBean alipayBean) throws BusinessException {
        // 支付宝网关地址
        String serverUrl ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
        //应用id
        String appId=aliConfigParam.getAppId();
        //应用私钥
        String privateKey =aliConfigParam.getRsaPrivateKey();

        // 格式化方式
        String format=aliConfigParam.getFormat();
        // 编码方式
        String  charset = aliConfigParam.getCharest();
        // 支付宝公钥
        String alipayPublicKey =aliConfigParam.getAlipayPublicKey();
        // 签名类型
        String signType = aliConfigParam.getSigntype();

            DefaultAlipayClient alipayClient = new DefaultAlipayClient(serverUrl,
                    appId, privateKey, format, charset, alipayPublicKey,signType);
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setReturnUrl(aliConfigParam.getReturnUrl());
            request.setNotifyUrl(aliConfigParam.getNotifyUrl());
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setBody(alipayBean.getBody());
        model.setOutTradeNo(alipayBean.getOutTradeNo());
        model.setSubject(alipayBean.getSubject());
        model.setTotalAmount(alipayBean.getTotalAmount());
        model.setProductCode(alipayBean.getProductCode());
        model.setTimeoutExpress(alipayBean.getExpireTime());
        request.setBizModel(model);
        String jsonAlipaybean = JSON.toJSONString(alipayBean);
        log.error("createPayOrderByAliWAP..alipayRequest:{}",jsonAlipaybean);

            AlipayTradeWapPayResponse payResponse=null;
        PaymentResponseDTO<String> res=null;
        try {
                payResponse = alipayClient.pageExecute(request);
                res= new PaymentResponseDTO<>();
                String body = payResponse.getBody();
                res.setContent(body);
            PaymentResponseDTO<AliConfigParam> msgDto = new PaymentResponseDTO<>();
            msgDto.setContent(aliConfigParam);//公共参数
            msgDto.setOutTradeNo(alipayBean.getOutTradeNo()); //商户订单号
            msgDto.setMsg("ALIPAY_WAP");   //支付渠道
            payProducer.payOrderNotice(msgDto);
        } catch (AlipayApiException e) {
                e.printStackTrace();
                throw new BusinessException(CommonErrorCode.E_400002);
            }
        return res;
        }

    @Override
    public PaymentResponseDTO<?> queryPayOrderByCli(AliConfigParam aliConfigParam, String outTradeNo) throws BusinessException {
// 支付宝网关地址
        String serverUrl ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
        //应用id
        String appId=aliConfigParam.getAppId();
        //应用私钥
        String privateKey =aliConfigParam.getRsaPrivateKey();

        // 格式化方式
        String format=aliConfigParam.getFormat();
        // 编码方式
        String  charset = aliConfigParam.getCharest();
        // 支付宝公钥
        String alipayPublicKey =aliConfigParam.getAlipayPublicKey();
        // 签名类型
        String signType = aliConfigParam.getSigntype();

        DefaultAlipayClient alipayClient = new DefaultAlipayClient(serverUrl,
                appId, privateKey, format, charset, alipayPublicKey,signType);

        //查询的请求对象
        AlipayTradeQueryRequest alipayrequest = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",outTradeNo);
        alipayrequest.setBizContent(jsonObject.toJSONString());
        try {
            //调支付宝查询接口
            AlipayTradeQueryResponse queryResponse = alipayClient.execute(alipayrequest);
            log.info("[代理服务查询支付结果]:{}",JSONObject.toJSONString(queryResponse));
            String code = queryResponse.getCode();
            //看是否查到结果
            if (AliCodeConstants.SUCCESSCODE.equals(code)){
           //有结果
                //将支付宝返回状态转为我们平台状态
                TradeStatus tradeStatus = this.converAliTradeStateTohuiminCode(queryResponse.getTradeStatus());
                return PaymentResponseDTO.success(queryResponse.getTradeNo(),queryResponse.getOutTradeNo(),tradeStatus,queryResponse.getMsg()+""+queryResponse.getSubMsg());
            }else {
                //无结果
        return PaymentResponseDTO.fail("交易结果未知",outTradeNo, TradeStatus.UNKNOWN);
            }
        } catch (AlipayApiException e) {
            throw new BusinessException(CommonErrorCode.E_100104);
        }
    }
    private TradeStatus converAliTradeStateTohuiminCode(String aliTradeStatus){
      switch (aliTradeStatus){
          case AliCodeConstants.WAIT_BUYER_PAY:
              return TradeStatus.USERPAYING;
          case AliCodeConstants.TRADE_SUCCESS:
          case AliCodeConstants.TRADE_FINISHED:
              return TradeStatus.SUCCESS;
          case AliCodeConstants.TRADE_CLOSED:
              return TradeStatus.REVOKED;
          default:
              return TradeStatus.FAILED;
      }
    }


}
